lh.cache.amList = [];
lh.timmerAry = [];
MY_SWIPER = null;
$(function(){
	init();
	callPageFun();//出价键盘事件
	initPage();
	initData();
	loadAuctionMicro();//加载专场
	lh.scrollBottom(loadAuctionMicro);//下拉加载更多数据
});

function init(){
	$(".com").attr("class","com");
	$("#weipai").attr("class","com orange");
	initPullToRefresh();
}

function showImgs(picPaths){
	commonShowImgs(picPaths, '320w', '500w');
}

function initPage(){
	
	if(lh.param.amSerial){
		$("#showAllMyDiv").show();
	}
	if(lh.param.goodsName){
		$("#showAllDiv").show();
	}
	
	/*MY_SWIPER = new Swiper ('.swiper-container', {
	    direction: 'horizontal',
	    loop: true,
	    pagination: '.swiper-pagination', // 如果需要分页器
	    nextButton: '.swiper-button-next',// 如果需要前进后退按钮
	    prevButton: '.swiper-button-prev',
	    scrollbar: '.swiper-scrollbar' // 如果需要滚动条
	  });*/
	
	$.mCustomScrollbar.defaults.theme = "light-2"; //set "light-2" as the default theme
	$("#ho1,#ho2").mCustomScrollbar({
		axis : "x",
		advanced : {
			autoExpandHorizontalScroll : true
		}
	});
	lh.plugins.template = $('#template').html();
	Mustache.parse(lh.plugins.template);   // optional, speeds up future uses
	
	lh.plugins.templateOffers = $('#template_offers').html();
	Mustache.parse(lh.plugins.templateOffers);   // optional, speeds up future uses
}

function initData(){
	
}

function countDown(auctionId, seconds, hour_elem, minute_elem, second_elem) {
    var timer = setInterval(function () {
        if (seconds > 0) {
            seconds --;
            /*var day = Math.floor((sys_second / 3600) / 24);*/
            var hour = Math.floor(seconds / 3600);
            var minute = Math.floor((seconds / 60) % 60);
            var second = Math.floor(seconds % 60);
            $(hour_elem).text(hour < 10 ? "0" + hour : hour);//计算小时
            $(minute_elem).text(minute < 10 ? "0" + minute : minute);//计算分
            $(second_elem).text(second < 10 ? "0" + second : second);// 计算秒
        } else {
            clearInterval(timer);
        	auctionOver(auctionId);
        }
    }, 1000);
    if(seconds == 0){
    	$('#am_'+auctionId).remove();//时间结束时移除
    }
    lh.timmerAry.push(timer);
}

/**清空所有倒计时timmer*/
function clearAllInterval(){
	for(var i in lh.timmerAry){
		clearInterval(lh.timmerAry[i]);
	}
}

function loadMyAllAuctionMicro(){
	lh.param.amSerial = null;//加载所有我的微拍
	lh.page.currentPage = 1;
	$("#showAllMyDiv").hide();
	clearAllInterval();
	$('#data-container').empty();
	loadAuctionMicro();
}

function loadAllAuctionMicro(){
	lh.param.goodsName = null;//加载所有我的微拍
	lh.page.currentPage = 1;
	$("#showAllDiv").hide();
	clearAllInterval();
	$('#data-container').empty();
	loadAuctionMicro();
}

function loadAllAuctionMicroBySearch(goodsName){
	lh.param.goodsName = goodsName;
	lh.page.currentPage = 1;
	$("#showAllDiv").show();
	clearAllInterval();
	$('#data-container').empty();
	loadAuctionMicro();
}

function loadAuctionMicro(amFlag){
	if(!amFlag)amFlag = lh.current.amFlag;
	 $('#auctionSwitchUl li').removeClass('active');
	 $('#am_'+amFlag).addClass('active');
	 if(amFlag != lh.current.amFlag){
		 lh.page.currentPage = 1;
		 $('#data-container').empty();
		 lh.current.amFlag = amFlag;
		 $("#showAllMyDiv").hide();
		 $("#showAllDiv").hide();
		 lh.param.amSerial = null;//点击了顶部切换按钮，就加载全部
		 lh.param.userSerial = null;
		 lh.param.goodsName = null;
	 }
	if(lh.page.currentPage == 1){
		 $('#data-container').empty();
	}
	lh.ajaxBefore();//ajax发起请求前执行
	var param = {amFlag:"focus", page:lh.page.currentPage, rows:lh.page.rows, notOver:1};
	var amSerial = lh.param.amSerial;
	var userSerial = lh.param.userSerial;
	var goodsName = lh.param.goodsName;
	var goodsName = lh.param.goodsName;
	//var userId = lh.param.userId;
	//if(userId)param.userId = userId;
	if(amSerial)param.amSerial = amSerial;
	if(userSerial)param.userSerial = userSerial;
	if(goodsName)param.goodsName = goodsName;
	lh.post('front', '/getAuctionMicroList', param, function(rsp){
		$('#loadingTip').hide();
		if(rsp.success){
			var data = rsp.rows;
			if(data && data.length>0){
				makeAuctionMicroDom(data, true);
				lh.page.currentPage ++;
			}else{
				$('#resultTip').text('没有更多数据').show();
			}
		}else{
			lh.page.currentPage = 1;
			$('#resultTip').text(rsp.msg).show();
		}
	},'json');
}

function makeAuctionMicroDom(data, isAppend){
	for(var i = 0; i<data.length; i++){
		var am = data[i];
		if(am.userAvatar){
			am.userAvatar += buildOSSZoom(50, 50); //@@_OSS_IMG_@@
		}else{
			am.userAvatar = '/images/front/default_avatar.png';
		}
		lh.cache.amList = _.concat(lh.cache.amList, data);
		var amoAry = am.amoList;
		if(amoAry && amoAry.length > 0){
			for(var j = 0; j < amoAry.length; j++){
				var amo = amoAry[j];
				if(amo.userAvatar){
					amo.userAvatar += buildOSSZoom(50, 50); //@@_OSS_IMG_@@
				}else{
					amo.userAvatar = '/images/front/default_avatar.png';
				}
				//amo.offerAt = moment().from(amo.offerAt); 
				amo.offerAt = lh.formatDate({date:new Date(amo.offerAt), flag:'datetime'});
				if(amo.offerPrice == am.offerPrice){
					amo.priceLead = 1;
				}
			}
		}
		if(am.postageFee == 2){
			am.postageFee = "";
		}
		if(am.isSevenReturn == 2){
			am.isSevenReturn = "";
		}
		if(data[i].creditMargin == 0){
			data[i].creditMargin = "";
		}
		var auctionId = am.id;
		autoRefreshOffer(auctionId);//自动定时刷新出价
		countDown(auctionId, am.remainSeconds, '#ctdown_hour_'+auctionId, '#ctdown_minute_'+auctionId, '#ctdown_second_'+auctionId);
	}
	var data = {
		rows:data,
		picsDom:function(){
			var goodsPicPaths = this.goodsPicPaths;
			if(!goodsPicPaths)return '';
			var pics = goodsPicPaths.split(',');
			var length = pics.length;
			if(length > 9)length = 9;
			var picsDom = '';
			for(var i=0;i<length;i++){
				var pic = pics[i];
				//TODO
				//pic += '@120h_120w_1e_1c_50Q'; //OSS图片@100h_100w_1e_1c
				pic += buildOSSZoom(150, 150); //@@_OSS_IMG_@@
				picsDom += '<li><img src="'+pic+'" width="150" style="max-width:98%"/></li>';//80
			}
			return picsDom;
		},
		picPathAry:function(){
			var goodsPicPaths = this.goodsPicPaths;
			if(!goodsPicPaths)return '';
			var pics = goodsPicPaths.split(',');
			var length = pics.length;
			var picPathAry = [];
			for(var j=0;j<length;j++){
				var pic = pics[j];
				picPathAry[j] = pic + '@320w_50Q'; //@@_OSS_IMG_@@
			}
			return picPathAry;
		},
		/*picNum:function(){
			var goodsPicPaths = this.asg.goodsPicPaths;
			var pics = goodsPicPaths.split(',');
			var length = pics.length;;
			if(length > 9)length = 9;
			return length;
		},*/
		date:function(){
			var createdAt = this.createdAt;
			createdAt = lh.formatDate(new Date(createdAt));
			return createdAt;
		},
		focusDom:function(){
			var overFoucs = this.overFoucs;
//			alert(overFoucs);
			var focusDom = '<a class="weui_btn weui_btn_mini weui_btn_plain_primary" href="javascript:void(0);" role="1" id="userFocus_userId_'+this.userId+'" onclick="joinFans(\''+this.userId+'\');return false;">+关注</a>';
			if(overFoucs && overFoucs > 0){
				focusDom = '<a class="weui_btn weui_btn_mini weui_btn_plain_primary" href="javascript:void(0);" role="2" id="userFocus_userId_'+this.userId+'" onclick="cancleFans(\''+this.userId+'\');return false;">取消关注</a>';
			}
			return focusDom;
		}
    }
	var rendered = Mustache.render(lh.plugins.template, data);
	//isAppend = false;//临时
	if(isAppend){
		$('#data-container').append(rendered);
	}else{
		$('#data-container').html(rendered);
	}
}


//取消关注
function cancleFans(fansId){
	var param = {fansId:fansId}
		lh.post('front', '/cancelFans', param, function(rsp) {
		if (rsp.success) {
		$('#userFocus_userId_'+fansId).removeClass('a_qxgz').addClass('a_gz').text('+关注').attr('role',1);
			var data = rsp.rows;
		} else {
			lh.alert(rsp.msg);
		}
	}, 'json');
}
//添加关注
function joinFans(fansId){
	var userId = $("#userId").val();
	if(userId == fansId){lh.alert('不能关注你自己');return;}
	var param = {fansId:fansId}
		lh.post('front', '/joinFans', param, function(rsp) {
		if (rsp.success) {
		$('#userFocus_userId_'+fansId).removeClass('a_gz').addClass('a_qxgz').text('取消关注').attr('role',2);
		} else {
			lh.alert(rsp.msg);
		}
	}, 'json');
}



function doBid(){
	var price = $('#numView').text();
	$('#topPrice').val(price);
	doOffer('save');
	hideCallActionSheet();
}

function doBuyout() {
	var buyoutPrice = lh.current.buyoutPrice[lh.current.auctionId];
	if(buyoutPrice){
		var offerPrice = $('#numView').text(buyoutPrice);
		doOffer('save');
		//hideCallActionSheet();
	}else{
		lh.alert('本次拍卖没有设置一口价');return;
	}
}

function doOffer(operation, auctionId, bail){
	//	/currentOfferPrice
	if(operation == 'show'){
		$("#topPrice").val('');
		lh.current.auctionId = auctionId;
		lh.current.bail = bail;
		var price = $('#top_offer_'+auctionId).text();
		var buyoutPrice = $('#buyoutPrice_'+auctionId).text();
		if(!buyoutPrice || buyoutPrice=='无')buyoutPrice = null;
		bail = $('#bail_'+auctionId).text();
		var increaseRangePrice = $('#increaseRangePrice_'+auctionId).text();
		if(!increaseRangePrice)increaseRangePrice = 1;
		if(bail)bail = new Number(bail);
		if(buyoutPrice)buyoutPrice = new Number(buyoutPrice);
		price = price.trim();
		price = new Number(price);
		increaseRangePrice = new Number(increaseRangePrice);
		var nextPrice = price + increaseRangePrice;
		
		if(!lh.current.increaseRangePrice)lh.current.increaseRangePrice = {};
		if(!lh.current.nextPrice)lh.current.nextPrice = {};
		if(!lh.current.buyoutPrice)lh.current.buyoutPrice = {};
		if(!lh.current.bail)lh.current.bail = {};
		
		lh.current.increaseRangePrice[auctionId] = increaseRangePrice;
		lh.current.nextPrice[auctionId] = nextPrice;
		lh.current.buyoutPrice[auctionId] = buyoutPrice;
		lh.current.bail[auctionId] = bail;
		showCallActionSheet({opt:'amBid', price:price, nextPrice:nextPrice, buyoutPrice:buyoutPrice});//call面板
	}else if(operation == 'cancel'){
		lh.current.auctionId = null;
		hideCallActionSheet();//call面板
	}else if(operation == 'save'){
		var auctionId = lh.current.auctionId;
		var bail = lh.current.bail[auctionId];
		var buyoutPrice = lh.current.buyoutPrice[auctionId];
		var increaseRangePrice = lh.current.increaseRangePrice[auctionId];
		
		var r = $("#r").val();
		if(!auctionId || !auctionId)return;
		var offerPrice = $('#numView').text();
		if(!offerPrice || offerPrice <= 0){
			lh.alert('请输入您的出价');return;
		}
		offerPrice = new Number(offerPrice);
		var nextPrice = lh.current.nextPrice[auctionId];
		if(offerPrice < nextPrice){
			lh.alert('加价幅度不能小于' + increaseRangePrice);return;//加价幅度不满足要求
		}
		//var creditMoney = $('#creditMoney').val();
		var creditMoney = lh.param.creditMoney;
		//var shopPrice = $('#shopPrice_'+asgId).val();
		var url = location.href;
		if(url.indexOf('?')>0){
			url += '&amId=' + auctionId;
		}else{
			url += '?amId=' + auctionId;
		}
		if(!checkAuctionMicroBail(bail, creditMoney, url, auctionId))return;
		if(buyoutPrice > 0 && offerPrice >= buyoutPrice){
			offerPrice = buyoutPrice;
		}
		lh.post('front', '/addAuctionMicroOffer',{auctionId:auctionId, offerPrice:offerPrice, promoteUserSerial:r},function(rsp){
			$('#call_actionsheet_cancel').click();//先关闭出价面板
			if(rsp.success){
				if(rsp.jumpToPayAuctionMicroOrder){//一口价，直接跳往支付页面
					lh.alert('一口价成交，前往支付页面', lh.reload);return;
					lh.jumpR('/user');
				}else{
					lh.alert('您已经成功出价', '提示');
				}
			}else{//相同代码：auctionMicroAdd.js,auctionMicro.js
				if(rsp.code == 'creditMoney_null'){
					lh.param.moneyLack = rsp.moneyLack;
					lh.param.bail = rsp.bail;
					lh.confirm('该场拍卖需要交纳'+rsp.moneyLack+'元保证金，是否交纳保证金？', '提示', doCreditMoneyPay);
				}else if(rsp.code == 'creditMoney_lack'){
					lh.param.moneyLack = rsp.moneyLack;
					lh.param.bail = rsp.bail;
					lh.confirm('您目前交纳的保证金为'+rsp.creditMoney+'元，该场拍卖需要交纳'+rsp.bail+'元保证金，是否增加交纳保证金？', '提示', doCreditMoneyPay);
				}else if(rsp.code == 'jumpToMyShop'){
					lh.confirm(rsp.msg, "lh.jumpR('/myShop')");
				}else{
					lh.alert(rsp.msg, '提示');
					lh.page.currentPage = 1;
				}
			}
			checkLastOffer(auctionId);//刷新报价
		},'json');
	}
}

function doCreditMoneyPay(){
	if(lh.param.moneyLack){
		localStorage.setItem("fromUrl", location.href);
		lh.jumpR('/creditMoney?from=am&bail='+lh.param.bail);
	}
}

function autoRefreshOffer(auctionId){
	 var timer = setInterval(function () {
        checkLastOffer(auctionId);
    	/*if (sys_second > 0) {
            clearInterval(timer);
        }*/

    }, 50000);//每50秒刷新一次
}

function checkLastOffer(auctionId){
	if(!auctionId)return;
	lh.post('front', '/getAuctionMicroOffer',{auctionId:auctionId},function(rsp){
		if(rsp.success){
			var asoList = rsp.asoList;
			var freshAm = rsp.am;
			if(!asoList)return;
			var am = _.find(lh.cache.amList, {'id': auctionId});
			am = freshAm;
			am.asoList = asoList;
			appendOffers(am);
		}
	},'json');
}

function appendOffers(am){
	var auctionId = am.id;
	var domOuterId = '#offer_container_'+auctionId;
	var asoList = am.asoList;
	var offerLength = asoList.length;
	if(offerLength > 0){
		for(var j = 0;j<offerLength;j++){
			var aso = asoList[j];
			//aso.offerAt = moment().from(aso.offerAt); 
			aso.offerAt = lh.formatDate(new Date(aso.offerAt));
			if(aso.offerPrice == am.offerPrice){
				aso.priceLead = 1;
			}
		}
	}
	
	var topOfferId = '#top_offer_'+auctionId;
	var price = am.offerPrice || am.priceBegin || 0;
	$(topOfferId).text(price);
	if(!lh.current.increaseRangePrice){
		var increaseRangePrice = 1;
	}else{
		var increaseRangePrice = lh.current.increaseRangePrice[auctionId];
	}
	$('#topPrice').val(price + increaseRangePrice);//更新输入价格框，默认提高1元
	var rendered = Mustache.render(lh.plugins.templateOffers, {rows:asoList});
	$(domOuterId).html(rendered);
}

function auctionOver(auctionId){
	lh.post('front', '/finishAuctionMicro',{auctionId:auctionId},function(rsp){
		if(rsp.success){
			var remainSeconds = rsp.remainSeconds;
			if(remainSeconds){
				countDown(auctionId, remainSeconds, '#ctdown_hour_'+auctionId, '#ctdown_minute_'+auctionId, '#ctdown_second_'+auctionId);
			}else{
				$('#am_'+auctionId).remove();
			}
		}
	},'json');
}

function toggleDescription(id){
	var $dom = $('#desc_'+id);
	var r = $dom.attr('role');
	if(r == 1){
		$dom.css('max-height','none');
		$dom.attr('role', 2);
		$('#desc_div_'+id+' a').text('收起');
	}else{
		$dom.css('max-height','94px');
		$dom.attr('role', 1);
		$('#desc_div_'+id+' a').text('展开');
	}
}

function showShare(){
	$('#shareMask,#share').show();
}
function hideShare(){
	$('#shareMask,#share').hide();
}

function togglePraise(amId, userId){
	var role = $('#praise_btn_'+asgId).attr('role');
	if(role == 1){
		addPraise(asgId, userId);
	}else{
		cancelPraise(asgId, userId);
	}
}

function addPraise(amId, userId){
	var obj ={praiseType:2, praiseId:amId};
	lh.post('front', '/addOrUpdateUserPraise', obj, function(rsp){
		if(rsp.success){
			if(rsp.code == "alreadyExist_error"){
				lh.praise = {amId:amId, userId:userId};
				lh.confirm('您已经点过赞了，是否取消点赞？', cancelPraise);
				return;
			}
			$('#praise_btn_'+amId).attr('role', 2);
			//$('#praise_text_'+asgId).text('取消点赞');
			var praiseId = rsp.praiseId;
			var avatar = rsp.userAvatar;
			appendPraise(amId, userId, praiseId, avatar);
		}
	},'json');
}

function cancelPraise(amId, userId){
	if(!amId){
		amId = lh.praise.amId;
		userId = lh.praise.userId;
		lh.praise = null;
	}
	var obj ={praiseType:2, praiseId:amId};
	lh.post('front', '/deleteUserPraise',obj,function(rsp){
		if(rsp.success){
			var praiseId = rsp.praiseId;
			$('#praise_'+praiseId).remove();
			$('#praise_btn_'+amId).attr('role',1);
			//$('#praise_text_'+asgId).text('点赞');
			var num = $('#praiseNum_'+amId).text();
			if(!num)num = 0;
			num = parseInt(num);
			$('#praiseNum_'+amId).text(--num);
			
		}
	},'json');
}

function appendPraise(amId, userId, praiseId, avatar){
	if(!amId || !userId || !praiseId)return;
	var dom = 
	'<div id="praise_'+praiseId+'" class="col-xs-2 pl0 pr7 pb5">'+
		'<img src="'+avatar+'" width="36" class="img-responsive">'+
	'</div>';
	$('#praise_container_'+amId).prepend(dom);
	var num = $('#praiseNum_'+amId).text();
	if(!num)num = 0;
	num = parseInt(num);
	$('#praiseNum_'+amId).text(++num);
	
}

function promptSearch(){
	/*$.prompt({
	  title: '标题',
	  text: '内容文案',
	  input: '请输入藏品名称',
	  empty: false, // 是否允许为空
	  onOK: function (input) {//点击确认
	    loadAllAuctionMicroBySearch(input);
	  },
	  onCancel: function () { //点击取消
	  }
   });*/
   $.prompt("请输入需要搜索的拍品名称", function(text) {
	   loadAllAuctionMicroBySearch(text);
	}, function() {//点击取消后的回调函数
	});
}


